package net.lcqf.udp.send;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import net.lcqf.udp.kcp.Ukcp;
import net.lcqf.udp.server.MsgInfo;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 各种类型消息
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/3/19 09:10
 * // +----------------------------------------------------------------------
 */

@Component
public class MessageFactory {
    private static final Map<Integer, MessageBaseService> MESSAGE = new HashMap<>();

    // 使用 PooledByteBufAllocator（池化）
    private static final ByteBufAllocator allocator = PooledByteBufAllocator.DEFAULT;

    public static void register(Integer type, MessageBaseService messageBaseService) {
        Assert.notNull(type, "type must not be null");
        Assert.notNull(messageBaseService, "messageBaseService must not be null");
        Assert.isNull(MESSAGE.putIfAbsent(type, messageBaseService),"type already exists");
    }

    public Object sendMessage(Ukcp kcp, MsgInfo msgInfo) {
        MessageBaseService tClass = MESSAGE.get(msgInfo.getRequestType());
        return Optional.ofNullable(tClass.sendMessage(kcp, msgInfo)).orElse(defaultMessage());
    }

    /**
     * 转ByteBuf
     * @param msgInfo 消息
     * @return {@code ByteBuf}
     */
    public static ByteBuf serializeToByteBuf(String msgInfo) {
        // 使用 Unpooled.buffer()（非池化）
        //ByteBuf byteBuf = Unpooled.buffer();

        // 使用 PooledByteBufAllocator（池化）
        ByteBuf byteBuf = allocator.buffer();
        byteBuf.writeBytes(msgInfo.getBytes(StandardCharsets.UTF_8));
        return byteBuf;
    }

    private Object defaultMessage() { return null; }
}
